"use strict";
const Service = require("egg").Service;
var Sequelize = require('sequelize');
const { httpCode } = require("../../utils/userConfig");
const SystemErrException = require("../../exception/systemError");

class MenuService extends Service {

  async updateMenu(menu) {
    try {
      const { ctx } = this;
      let id = menu.id;
      delete menu.id;
      await ctx.model.Sys.Menu.update(menu, {
        where: { id }
      })
      return {
        code: httpCode.SUCCESS,
        message: '更新成功！'
      }
    } catch (error) {
      throw new SystemErrException("菜单更新异常：" + error.message);
    }
  }

  async deleteMenu(id) {
    try {
      const { ctx } = this;
      const childMenus = await ctx.model.Sys.Menu.findAll({
        where: {
          parent_id: id
        }
      });
      if (childMenus.length === 0) {
        await ctx.model.Sys.Menu.destroy({
          where: { id }
        })
        return {
          code: httpCode.SUCCESS,
          message: '删除成功！'
        }
      } else {
        return {
          code: httpCode.LOGICERROR,
          message: '请先删除子菜单或按钮！'
        }
      }
    } catch (error) {
      throw new SystemErrException("菜单删除失败：" + error);
    }
  }

  async addMenu(menu) {
    try {
      const { ctx } = this;
      const result = await ctx.model.Sys.Menu.create(menu);
      return {
        data: result,
        code: httpCode.SUCCESS,
        message: (menu.type === 1 ? '菜单' : '按钮') + '添加成功！'
      }
    } catch (error) {
      throw new SystemErrException("菜单添加异常：" + error);
    }
  }

  async getMenuTree() {
    try {
      const { ctx } = this;
      const menus = await ctx.model.Sys.Menu.findAll({
        where: {
          type: 1
        },
        order: [['order', 'asc']], // 排序规则
      });
      // 组装菜单树
      let menuTree = (function makeTreeData(arr, parentId) {
        let temp = []
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].parentId === parentId) {
            let item = arr[i];
            let menu = {
              label: item.title,
              value: item.id
            }
            temp.push(menu)
            let filterMenu = makeTreeData(menus, menu.value);
            if (filterMenu.length > 0) {
              menu.children = makeTreeData(menus, menu.value)
            }
          }
        }
        return temp
      })(menus, null)
      return {
        data: menuTree,
        code: httpCode.SUCCESS,
        message: '成功获取菜单树'
      }
    } catch (error) {
      throw new SystemErrException("获取菜单树异常：" + error);
    }
  }

  async getMenus() {
    try {
      const { ctx } = this;
      const menus = await ctx.model.Sys.Menu.findAll({
        order: [['order', 'asc']], // 排序规则
      });
      const menusObj = JSON.parse(JSON.stringify(menus));
      let allMenus = (function makeTreeData(arr, parentId, parentIds) {
        let temp = []
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].parentId === parentId) {
            let menu = JSON.parse(JSON.stringify(arr[i]));
            if (menu.parentIds) {
              menu.parentIds = Array.from(new Set([...menu.parentIds].filter(Boolean)))
            } else {
              menu.parentIds = Array.from(new Set([menu.parentIds].filter(Boolean)))
            }
            temp.push(menu)
            parentIds = [...parentIds, menu.parentId].filter(Boolean)
            let filterMenu = makeTreeData(menusObj, menu.id, parentIds);
            if (filterMenu.length > 0) {
              filterMenu.forEach(item => {
                item.parentIds = Array.from(new Set([...parentIds, item.parentId].filter(Boolean)))
              })
              menu.children = filterMenu;
            }
          }
        }
        return temp
      })(menusObj, null, [])

      // 排序     
      allMenus.sort((a, b) => a.order - b.order)

      return {
        data: allMenus,
        code: httpCode.SUCCESS,
        message: '成功获取菜单树'
      }
    } catch (error) {
      throw new SystemErrException("获取菜单异常：" + error);
    }
  }
}

module.exports = MenuService;
